package com.huidz.calendar.net;

import android.util.Log;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitServier {
    private static RetrofitServier singleton;
    private Retrofit retrofit;
    private final APIServer apiServer;

    public APIServer getApiServer() {
        return apiServer;
    }

    private RetrofitServier() {

        OkHttpClient mClient = new OkHttpClient.Builder()
                .addInterceptor(interceptor)
//                .connectTimeout(30, TimeUnit.SECONDS)
//                .writeTimeout(10,TimeUnit.MINUTES)
//                .readTimeout(10,TimeUnit.MINUTES)
                .build();
        //这行必须加 不然默认不打印
        // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        Retrofit retrofit = new Retrofit
                .Builder()
                .baseUrl(UrlConfig.URL)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // 使用RxJava作为回调适配器
//                .addConverterFactory(new ToStringConverterFactory())
                .addConverterFactory(GsonConverterFactory.create())
//                .client(mClient)
                .build();
        apiServer = retrofit.create(APIServer.class);
    }

    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
        @Override
        public void log(String message) {
            try {
                String text = URLDecoder.decode(message, "utf-8");
                Log.e("xpg", text);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                Log.e("xpg", message);
            }
        }
    });

    public static synchronized RetrofitServier getInstance() {
        if (singleton == null) {
            singleton = new RetrofitServier();
        }
        return singleton;
    }


}
